package com.taotao.order.service.impl;

import com.taotao.common.redis.service.RedisService;
import com.taotao.common.security.utils.SecurityUtils;
import com.taotao.order.constants.OrderConstants;
import com.taotao.order.domain.Order;
import com.taotao.order.domain.PaymentFlow;
import com.taotao.order.domain.request.OrderMessage;
import com.taotao.order.mapper.OrderMapper;
import com.taotao.order.service.OrderService;
import com.taotao.product.domain.SkuInventoryQuantity;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @className: OrderServiceImpl
 * @author: ZhangYuQi
 * @date: 2025/2/5 下午7:49
 * @Version: 1.0
 * @description:
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisService redisService;


    @Override
    public void addTransactionFlows(PaymentFlow paymentFlow) {
        orderMapper.insertPaymentFlow(paymentFlow);
    }

    @Override
    public PaymentFlow findByTradeNo(String tradeNo) {
        return orderMapper.selectByTradeNo(tradeNo);
    }

    @Override
    public String placeAnOrder(OrderMessage orderMessage) {

        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 获取当前时间，并格式化
        String formattedCurrentTime = LocalDateTime.now().format(formatter);

        // 实例化Random对象
        Random random = new Random();

        // 生成四位数的随机数（0到9999之间），确保为四位数（前导零）
        int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机整数
        // 生成订单号
        String orderNum = "JD" + formattedCurrentTime + randomNumber;

        //存入消息对象
        orderMessage.setOrderNum(orderNum);

        //向redis中存入一个状态 前端轮询获取下单结果 设置超时时长
        redisService.setCacheObject(OrderConstants.ORDER_STATUS + orderNum, 0, 2L, TimeUnit.MINUTES);

        //获取当前登录用户id
        Long userId = SecurityUtils.getUserId();

        //构建消息对象
        orderMessage.setUserId(userId);

        System.out.println("发送消息：" + orderMessage);
        //发送消息 异步操作
        rabbitTemplate.convertAndSend("order.exchange", "order.routingKey", orderMessage);
        //rabbitTemplate.convertAndSend("test",orderMessage);
        System.out.println("发送消息成功");
        //返回订单号
        return orderNum;
    }

    @Override
    public void insertOrder(Order order) {
        orderMapper.insertOrder(order);
    }

    @Override
    public Integer selectOrderStatusByOrderNum(String orderNum) {
        //状态 0-代表下单中 1-代表下单成功 2-代表下单失败 null表示超时失败
        Integer status = redisService.getCacheObject(OrderConstants.ORDER_STATUS + orderNum);
        return status;
    }

    @Override
    public void insertSkuOrder(Long id, List<SkuInventoryQuantity> skuOrders) {
        orderMapper.insertSkuOrder(id, skuOrders);
    }
}
